import 'package:state_beacon/state_beacon.dart';

/// 关注状态管理
class FollowState {
  // 静态状态变量
  static Map<String, List<String>> _userFollowsMap = {};

  // State Beacon 实例
  static final userFollowsMapBeacon =
      Beacon.writable<Map<String, List<String>>>(_userFollowsMap);

  /// 初始化默认关注数据
  static void _initializeDefaultData() {
    if (_userFollowsMap.isNotEmpty) return; // 避免重复初始化

    // 初始化默认关注关系
    _userFollowsMap = {
      'admin': [
        'user_001', // LemurFan
        'user_003', // Chameleo
        'user_005', // GeckoEye
      ],
      'user_001': [
        'user_002', // BaobabX
        'user_004', // FossaPro
      ],
      'user_002': [
        'user_001', // LemurFan
        'user_003', // Chameleo
      ],
    };

    // 更新 Beacon 状态
    userFollowsMapBeacon.value = Map.from(_userFollowsMap);
  }

  /// 初始化状态
  static void initialize() {
    _initializeDefaultData();
  }

  /// 切换关注状态
  static bool toggleFollow(String userId, String targetUserId) {
    _initializeDefaultData();

    // 确保用户关注列表存在
    if (!_userFollowsMap.containsKey(userId)) {
      _userFollowsMap[userId] = [];
    }

    final userFollows = _userFollowsMap[userId]!;
    final index = userFollows.indexOf(targetUserId);

    if (index != -1) {
      // 已关注，取消关注
      userFollows.removeAt(index);
      userFollowsMapBeacon.value = Map.from(_userFollowsMap);
      return false;
    } else {
      // 未关注，添加关注
      userFollows.add(targetUserId);
      userFollowsMapBeacon.value = Map.from(_userFollowsMap);
      return true;
    }
  }

  /// 检查用户是否已关注目标用户
  static bool isFollowing(String userId, String targetUserId) {
    _initializeDefaultData();
    final userFollows = _userFollowsMap[userId];
    return userFollows?.contains(targetUserId) ?? false;
  }

  /// 获取用户的关注列表
  static List<String> getUserFollows(String userId) {
    _initializeDefaultData();
    return _userFollowsMap[userId] ?? [];
  }

  /// 获取用户的粉丝列表
  static List<String> getUserFollowers(String userId) {
    _initializeDefaultData();
    final followers = <String>[];

    _userFollowsMap.forEach((followerId, followList) {
      if (followList.contains(userId)) {
        followers.add(followerId);
      }
    });

    return followers;
  }

  /// 获取关注数量
  static int getFollowCount(String userId) {
    return getUserFollows(userId).length;
  }

  /// 获取粉丝数量
  static int getFollowerCount(String userId) {
    return getUserFollowers(userId).length;
  }

  // Getters for reactive state
  static ReadableBeacon<Map<String, List<String>>> get userFollowsMap =>
      userFollowsMapBeacon;
}
